<template>
  <div class="experimentCreate">
    <!--点开后看到的表单-->
    <el-form
      :model="form"
      ref="form"
      label-width="100px"
      v-loading="formLoading"
      :rules="rules"
    >
      <el-form-item label="实验名称：" prop="name" required>
        <el-input v-model="form.name" placeholder="请填写实验名称" />
      </el-form-item>
      <!--学校管理员登录才会出现-->
      <el-form-item
        v-if="this.userInfo.roleName == 'schoolAdmin' ||this.userInfo.roleName == 'teacher'"
        label="时间限制："
        required
        style="text-align: left"
      >
        <el-date-picker
          v-model="timeLimit"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="必做题题目:"
        prop="requiredQuestions"
        required
        style="text-align: left"
      >
        <el-button
          round
          icon="el-icon-plus"
          type="primary"
          size="mini"
          @click="addQuestion(true)"
          >添加题目</el-button
        >
        <el-card
          class="exampaper-item-box"
          v-if="form.requiredQuestions.length !== 0"
        >
          <el-form-item
            :key="index"
            :label="'题目' + (index + 1) + '：'"
            v-for="(item, index) in form.requiredQuestions"
          >
            <el-row>
              <el-col :span="21">
                <span>{{ item.id }}.{{ item.title }}</span>
              </el-col>
              <el-col :span="3" class="btn">
                <el-button  size="mini" type='primary' circle icon="el-icon-top"  @click="sortUp(index,form.requiredQuestions)"></el-button>
                <el-button  size="mini" type='primary' circle icon="el-icon-bottom" @click="sortDown(index,form.requiredQuestions)"></el-button>
                <el-button
                  circle
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="form.requiredQuestions.splice(index, 1)"
                >
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form-item>
      <el-form-item
        label="选做题题目:"
        prop="optionalQuestions"
        style="text-align: left"
      >
        <el-button
          round
          icon="el-icon-plus"
          type="primary"
          size="mini"
          @click="addQuestion(false)"
          >添加题目</el-button
        >
        <el-card
          class="exampaper-item-box"
          v-if="form.optionalQuestions && form.optionalQuestions.length !== 0"
        >
          <el-form-item
            :key="index"
            :label="'题目' + (index + 1) + '：'"
            v-for="(item, index) in form.optionalQuestions"
          >
            <el-row>
              <el-col :span="21">
                <span>{{ item.id }}.{{ item.title }}</span>
              </el-col>
              <el-col :span="3" class="btn">
              <el-button  size="mini" type='primary' circle icon="el-icon-top"  @click="sortUp(index,form.optionalQuestions)"></el-button>
                <el-button  size="mini" type='primary' circle icon="el-icon-bottom" @click="sortDown(index,form.optionalQuestions)"></el-button>
                <el-button
                  circle
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="form.optionalQuestions.splice(index, 1)"
                >
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>
      </el-form-item>
      <el-form-item label="备注：" prop="note">
        <el-input v-model="form.note" type="textarea" placeholder="请输入内容" maxlength="300" />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetForm" round type="info" class="reset">重置</el-button>
        <el-button
          :loading="submitLoading"
          type="primary"
          @click="submitForm"
          round
          >提交</el-button
        >
      </el-form-item>
    </el-form>
    <!--:visible.sync 布尔值是否显示dialog-->
    <el-dialog
      :visible.sync="questionPage.showDialog"
      width="70%"
      title="添加题目"
    >
      <!--题目查询第一行-->
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true">
        <el-form-item label="题目：">
          <el-input
            prefix-icon="el-icon-search"
            placeholder="请输入要查询的题目"
            v-model="questionPage.queryParam.title"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item style="padding-left: 10px" label="知识点：">
          <!--  filterable是否可搜索 clearable是否可清空-->
          <el-select
            v-model="questionPage.queryParam.tag"
            filterable
            placeholder="==请选择知识点=="
            clearable
            round
          >
            <el-option
              v-for="item in tags"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  round v-debounce="queryFormSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <div class="questionList">
        <!--fit	列的宽度是否自撑开 questionPage.tableData查询返回的实验-->
        <el-table
          v-loading="questionPage.listLoading"
          :data="questionPage.tableData"
          @selection-change="handleSelectionChange"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="id" label="Id" width="60px" />
          <el-table-column prop="title" label="题干" show-overflow-tooltip />
          <el-table-column
            prop="tag"
            align="center"
            label="知识点"
            width="200px"
          >
            <!--插槽，一个实验可以有多个标签-->
            <template v-slot="{ row }">
              <el-tag v-for="item in row.tags" :key="item.index">{{
                item.name
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            align="center"
            prop="level"
            label="难度"
            width="80px"
          >
            <template v-slot="{ row }">
              <span>{{ levelChange(row.level) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--获取到实验过多时需要分页-->
      <el-pagination
        v-show="questionPage.total > questionPage.queryParam.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="questionPage.queryParam.pageNum"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="questionPage.queryParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="questionPage.total"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="questionPage.showDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmQuestion">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllQuestion, getAllTag } from "@/api/question.js";
import {
  addExperiment,
  updateExperiment,
  addExperimentByschool,
} from "@/api/experiment.js";
export default {
  name: "experimentCreate",
  data() {
    return {
      tags: [], //标签
      form2: {},
      form: {
        note:"",
        //可选必选实验表单
        requiredQuestions: [],
        optionalQuestions: [],
      },
      //加载中，一个布尔值
      formLoading: false,
      //表单验证规则
      rules: {
        name: [{ required: true, message: "请输入实验名称", trigger: "blur" }],
      },
      isAdd: true,
      submitLoading: false,
      questionPage: {
        tableData: [], //实验列表
        required: null, //标志位required=true时 添加必选题
        showDialog: false, //true时弹出题目
        queryParam: {
          //请求实验列表的参数
          title: null,
          tag: null,
          type: 2,
          pageNum: 1,
          pageSize: 10,
        },
        multipleSelection: [], //选中的实验
        listLoading: false,
        total: 10, //实验总数
      },
      currentTitleItem: null,
      timeLimit: [], //限制时间
      userInfo: {}, //用户信息
      isAdd: true, //判断是添加还是编辑实验
    };
  },
  created() {
    this.$route.meta.title = "新建实验";
    if (this.$route.params.data) {
      this.form = this.$route.params.data;
      this.isAdd = false;
      if (this.form.limitDateTime) {
        this.timeLimit = this.form.limitDateTime;
      }
      this.$route.meta.title = "编辑实验";
    }

    this.userInfo = JSON.parse(localStorage.getItem("user"));
  },
  computed: {
    //这里不太懂 返回一个函数？
    levelChange() {
      let levels = ["easy", "medium", "hard"];
      return (val) => {
        return levels[val];
      };
    },
  },
  methods: {
     // 上移按钮
    sortUp (index,questions) {
      if (index === 0) {
        this.$message({
          message: '这已经是第一题！',
          type: 'warning'
        })
      } else {
        let temp = questions[index - 1]
        this.$set(questions, index - 1, questions[index])
        this.$set(questions, index, temp);
        console.log(questions);
      }
    },
        // 下移按钮
    sortDown (index,questions) {
      if (index === (questions.length - 1)) {
        this.$message({
          message: '已经是最后一题！',
          type: 'warning'
        })
      } else {
        let i = questions[index + 1]
        this.$set(questions, index + 1, questions[index]);
        this.$set(questions, index, i);
      }
    },
    //点击增加按钮触发
    addQuestion(index) {
      this.questionPage.required = index;
      //dialog点击后弹出
      this.questionPage.showDialog = true;
      //获取所有标签
      getAllTag().then((res) => {
        this.tags = res;
      });
      //获取实验列表
      this.getQuestions();
    },
    //选中题目、知识点后查询实验
    queryFormSearch() {
      this.questionPage.queryParam.pageNum = 1;
      this.getQuestions();
    },
    //根据标签/标题/题型获取题目
    getQuestions() {
      this.questionPage.listLoading = true;
      getAllQuestion(this.questionPage.queryParam)
        .then((res) => {
          this.questionPage.tableData = res.data;
          this.questionPage.total = res.total;
        })
        .finally(() => {
          this.questionPage.listLoading = false;
        });
    },
    //确定选中实验，dialog消失
    confirmQuestion() {
      this.confirmQuestionSelect();
      this.questionPage.showDialog = false;
    },
    //确定选中
    confirmQuestionSelect() {
      let target = this.questionPage.required
        ? this.form.requiredQuestions
        : this.form.optionalQuestions;
      this.questionPage.multipleSelection.forEach((item) => {
        if (
          !target.some((item2) => {
            //判断是否含有该题
            if (item.id == item2.id) return true;
          })
        ) {
          //不存在则添加进来  避免重复数据
          target.push(item);
        }
      });
      this.questionPage.multipleSelection = [];
    },
    //选项发生变化触发
    handleSelectionChange(val) {
      this.questionPage.multipleSelection = val;
    },
    //处理每页实验数变化
    handleSizeChange(size) {
      this.questionPage.queryParam.pageSize = size;
      this.confirmQuestionSelect();
      this.getQuestions();
    },
    //处理页面变化
    handleCurrentChange(page) {
      this.questionPage.queryParam.pageNum = page;
      this.confirmQuestionSelect();
      this.getQuestions();
    },
    //重置清空表单
    resetForm() {
      this.form = {
        requiredQuestions: [],
        optionalQuestions: [],
      };
    },
    //提交表单
    submitForm() {
      //数据提交验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          //暂存 若上传失败回显可正常
          let question1 = [];
          let question2 = [];
          this.submitLoading = true;
          question1 = this.form.optionalQuestions;
          question2 = this.form.requiredQuestions;
          this.form.optionalQuestions = this.form.optionalQuestions.map(
            (item) => {
              return item.id;
            }
          );
          this.form.requiredQuestions = this.form.requiredQuestions.map(
            (item) => {
              return item.id;
            }
          );
          //添加实验
          if (this.isAdd) {
            
            if (this.userInfo.roleName == "superAdmin") {
              this.form.id = 0;
              delete this.form.school;
              delete this.form.status;
              //超级管理员添加实验
              addExperiment(this.form)
                .then((res) => {
                  this.$message.success("新增成功");
                  this.$router.push({
                    name: "experimentModule/experimentList",
                    params: { mark: true },
                  });
                })
                .catch(() => {
                  this.$message.error("上传失败");
                  this.form.optionalQuestions = question1;
                  this.form.requiredQuestions = question2;
                })
                .finally(() => {
                  this.submitLoading = false;
                });
              return;
            }
            //校管理员添加实验
            let obj = {
              
              id:0,
              school: this.userInfo.schoolId,
              status: "ENABLE",
              startTime: this.timeLimit[0],
              endTime: this.timeLimit[1],
              ...this.form,
            };
            addExperimentByschool(obj, this.userInfo.userId)
              .then((res) => {
                this.$message.success("新增成功");
                this.$router.push({
                  name: "experimentModule/experimentList",
                  params: { mark: true },
                });
              })
              .catch(() => {
                this.$message.error("上传失败");
                this.form.optionalQuestions = question1;
                this.form.requiredQuestions = question2;
              })
              .finally(() => {
                this.submitLoading = false;
              });
          } else{
            //编辑实验
            delete this.form.statusLoading;
            delete this.form.creator;
            delete this.form.delLoading;
            delete this.form.editTimeLoading;
            delete this.form.limitDateTime; 
            delete this.form.creatorSchool;
            delete this.form.weight;
            delete this.form.experimentProblemResults;
            
            if (this.userInfo.roleName == "schoolAdmin" || this.userInfo.roleName == "teacher") {
              delete this.form.schoolId;
            } else {
              //delete this.form.schoolIds;
              delete this.form.schoolNames;
            }
            if (this.timeLimit.length == 0) {
              this.timeLimit = ["2020-01-01 12:00:00", "2200-01-01 12:00:00"];
            }
            (this.form.startTime = this.timeLimit[0]),
              (this.form.endTime = this.timeLimit[1]),
              console.log(this.form);
              console.log(this.userInfo.userId);
              updateExperiment(this.form, this.userInfo.userId)
                .then((res) => {
                  this.$message.success("修改成功");
                  this.$router.push({
                    name: "experimentModule/experimentList",
                    params: { mark: true },
                  });
                })
                .catch((err) => {
                  console.log(err);
                  this.$message.error("上传失败");
                  this.form.optionalQuestions = question1;
                  this.form.requiredQuestions = question2;
                })
                .finally(() => {
                  this.submitLoading = false;
                });
          }
        }
      });
    },
  },
};
</script>
<style scoped>
.el-select .el-input.is-focus .el-input__inner {
  border-radius: 20px;
}
.exampaper-item-box {
  box-shadow: none;
  border-color: white;
}
.el-card__body .el-form-item {
  border: 1px #dcdfe6 solid;
  margin-bottom: 12px;
  position: relative;
  width: 90%;
}
.el-card__body .el-form-item .btn {
  position: absolute;
  right: -130px;
  top: 2px;
}
.el-card__body .el-form-item >>> .el-form-item__label {
  color: #7986a6;
}
.el-input >>> .el-input__inner {
  border-radius: 30px;
}
.el-select >>> .el-input__inner {
  border-radius: 30px;
}
.reset {
  margin-left: 450px;
}

</style>